package com.fs.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.mapper.UserInfoMapper;
import com.fs.mapper.UserMapper;
import com.fs.pojo.User;
import com.fs.pojo.UserInfo;
import com.fs.vo.PageResult;
import com.fs.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userDao;

    @Autowired
    private UserInfoMapper userInfoDao;

    @Override
    @Transactional
    public SysResult addUser(Map<String, Object> request) throws ParseException {
        if (request == null) {
            return SysResult.fail();
        }
        String username = request.get("username").toString();
        String password = request.get("password").toString();
        String email = request.get("email").toString();
        String phone = request.get("phone").toString();
        String birthday1 = request.get("birthday").toString();
        Date birthday=null;
        if(birthday1 !=null && !"".equals(birthday1)) birthday= DateFormat.getDateInstance().parse(birthday1);
        Integer sex=null;
        String sex1 = request.get("sex").toString();
        if(sex1 !=null && !"".equals(sex1)) sex = Integer.valueOf(sex1);
        String addr = request.get("addr").toString();

        String balance1 = request.get("balance").toString();
        Integer balance=0;
        if(balance1!=null && !"".equals(balance1)) balance=Integer.valueOf(balance1);

        String score1 = request.get("score").toString();
        Integer score=0;
        if(score1!=null && !"".equals(score1)) score=Integer.valueOf(score1);


        if (username == null) {
            return SysResult.fail("请填写用户名");
        }

        //判断用户名是否符合规则
        String usernameRegex = "^\\w{5,16}$";
        if (!username.matches(usernameRegex)) return SysResult.fail("用户名5-16位，字母或数字");

        //判断密码是否符合规则
        String passwordRegex = "^\\w{5,16}$";
        if (!password.matches(passwordRegex)) return SysResult.fail("密码5-16位，字母或数字");

        String emailRegex = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";
        if (!email.matches(emailRegex)) return SysResult.fail("邮箱格式不正确");

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User selectOne = userDao.selectOne(queryWrapper);
        if (selectOne != null) {
            return SysResult.fail("账户重复");
        }

        Date date = new Date();
        String salt = RandomUtil.randomString(8);
        String md5 = SecureUtil.md5(password + salt);

        User userEntity = new User();
        userEntity.setUsername(username)
                .setEmail(email)
                .setPhone(phone)
                .setSalt(salt)
                .setPassword(md5)
                .setId(null)
                .setBalance(balance)
                .setScore(score)
                .setStatus(true)
                .setCreated(date)
                .setUpdated(date);
        int i = userDao.insert(userEntity);

        //更新附表
        UserInfo userInfoEntity = new UserInfo();
        userInfoEntity.setSex(sex)
                .setBirthday(birthday)
                .setAddr(addr)
                .setUserId(userEntity.getId());
        int i1 = userInfoDao.insert(userInfoEntity);

        if (i > 0 && i1 > 0) {
            return SysResult.success();
        }
        return SysResult.fail("用户添加失败");
    }

    @Override
    @Transactional
    public SysResult editUser(User user) {
        if (user == null) return SysResult.fail();

        if (user.getId() == null) return SysResult.fail("账户id有误");
        Integer id = user.getId();
        if (id < 1) return SysResult.fail("账户id有误");

        if (user.getPassword()!=null && !"".equals(user.getPassword())) {
            String salt = RandomUtil.randomString(8);
            String md5 = SecureUtil.md5(user.getPassword() + salt);
            user.setPassword(md5);
            user.setSalt(salt);
        }else{
            user.setPassword(null);
        }

        if (!StrUtil.isBlank(user.getEmail())) {
            String emailRegex = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";
            if (!user.getEmail().matches(emailRegex)) return SysResult.fail("邮箱格式不正确");
        }

        Date date = new Date();
        user.setUpdated(date);

        int i = userDao.updateById(user);
        UserInfo userInfoEntity=new UserInfo();
        userInfoEntity.setUserId(id)
                .setBirthday(user.getUserInfo().getBirthday())
                .setSex(user.getUserInfo().getSex())
                .setAddr(user.getUserInfo().getAddr());
        int i1 = userInfoDao.update(userInfoEntity, new UpdateWrapper<UserInfo>().eq("user_id", id));

        if (i > 0 && i1 > 0) {
            return SysResult.success();
        }

        return SysResult.fail("更新失败");
    }

    @Override
    public SysResult list(PageResult request) {
        Integer pageNum = request.getPageNum();
        Integer pageSize = request.getPageSize();
        if (pageNum < 0) pageNum = 1;
        if (pageSize < 0) pageSize = 10;
        Page<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!StrUtil.isBlank(request.getQuery()), "username", request.getQuery())
                .orderByDesc("id");
        page = userDao.selectPage(page, queryWrapper);
        request.setTotal(page.getTotal())
                .setRows(page.getRecords());
        return SysResult.success(request);
    }

    @Transactional
    @Override
    public SysResult changeStatus(Integer id, Boolean status) {
        User userEntity = new User();
        userEntity.setId(id).setStatus(status);
        userDao.updateById(userEntity);
        return SysResult.success();
    }

    @Transactional
    @Override
    public SysResult delById(Integer id) {
        userDao.deleteById(id);
        userInfoDao.delete(new QueryWrapper<UserInfo>().eq("user_id",id));
        return SysResult.success();
    }

    @Override
    public SysResult getById(Integer id) {
        UserInfo userInfo = userInfoDao.selectOne(new QueryWrapper<UserInfo>().eq("user_id", id));
        User user = userDao.selectById(id);
        user.setPassword(null).setSalt(null);
        user.setUserInfo(userInfo);
        return SysResult.success(user);
    }
}
